<template>
  <div class="login">
    <van-nav-bar title="会员登录" left-arrow @click-left="$router.back()" />
    <van-form class="login_form">
      <van-cell center title="手机号登录" title-class="title" label="未注册的手机号登陆后将自动注册" />
      <van-field v-model.trim="phoneNumber" name="phoneNumber" label="" placeholder="请输入手机号码" />
      <van-field v-model.trim="code" center label="" placeholder="请输入图形验证码" class="verify_code">
        <template #extra>
          <img @click="smsCode()" :src="imgUrl" alt="">
        </template>
      </van-field>

      <van-field v-model.trim="sms" label="" placeholder="请输入短信验证码">
        <template #button v-if="seconds === real_second">
          <van-button class="sms_btn" size="small" type="primary" @click="sendCode()">发送验证码</van-button>
        </template>
        <template #button v-else>
          <van-button class="sms_btn" :disabled="true" size="small" type="primary" @click="sendCode()">重新发送({{seconds}})秒</van-button>
        </template>
      </van-field>

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" class="login_btn" @click="login()">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { verifyPhone, verifyCode } from '@/utils/validator'
import { smsCode, verifyAndgetCode, codeLogin } from '@/apis/user'
// import { smsCode, verifyAndgetCode } from '@/apis/user'
import { mapMutations } from 'vuex'
// import { setToken } from '@/uitls/storage'
import { Toast } from 'vant'
export default {
  name: 'LoginIndex',
  data () {
    return {
      phoneNumber: '',
      password: '',
      imgUrl: '',
      timer: null,
      key: '',
      code: '',
      sms: '',
      isParty: false,
      partyData: {},
      // 倒计时
      seconds: 60, // 倒计时
      real_second: 60 // 实际的倒计时
    }
  },
  created () {
    // 图形验证码
    this.smsCode()
  },
  methods: {
    ...mapMutations('user', ['setLoginAuth']),
    // 手机验证码：必须带上正确的图形验证码，以及key，才能被标识，还有手机号
    async sendCode () {
      if (!verifyPhone(this.phoneNumber)) {
        return Toast('请输入正确格式的手机号')
      }
      if (!verifyCode(this.code)) {
        return Toast('请输入正确格式的验证码')
      }
      try {
        const res = await verifyAndgetCode({
          captchaCode: this.code, // 图形验证码
          captchaKey: this.key, // 图形验证码正确时候才会返回的key
          mobile: this.phoneNumber
        })
        if (!this.timer && this.seconds === this.real_second) {
          this.timer = setInterval(() => {
            // 倒计时
            if (this.seconds <= 1) {
              clearInterval(this.timer)
              // 打开开关
              this.timer = null
              this.seconds = this.real_second
              return
            }
            console.log(this.seconds, this.real_second)
            this.seconds--
          }, 1000)
        }
        Toast(res.message)
      } catch (error) {
        Toast(error)
      }
    },
    async login () {
      if (!verifyPhone(this.phoneNumber)) {
        return Toast('请输入正确格式的手机号')
      }
      if (!verifyCode(this.code)) {
        return Toast('请输入正确格式的验证码')
      }
      if (this.sms.trim === '') {
        return Toast('短信验证码不能为空')
      }
      // 调用一下图形验证码
      try {
        const { data } = await codeLogin({
          isParty: this.isParty,
          mobile: this.phoneNumber,
          partyData: this.partyData,
          smsCode: this.sms
        })
        Toast('登录成功')
        // 登录成功，将token和userId存到vuex，并且通过localStorage进行存储
        this.setLoginAuth(data.token)
        this.$router.back()
      } catch (err) {
        console.log(err)
        // 失败，刷新一下图形验证码
        this.smsCode()
      }
    },
    // 图形验证码
    smsCode () {
      // 节流处理，在1s内点击多少次都没有用，等到1s过后才会生效
      if (!this.timer) {
        this.timer = setTimeout(async () => {
          const {
            data: { base64, key }
          } = await smsCode()
          this.imgUrl = base64
          this.key = key
          clearInterval(this.timer)
          this.timer = null
        }, 500)
      }
    }
  },
  destroyed () {
    // 清除定时器
    clearInterval(this.timer)
  }
}
</script>

<style lang="less" scoped>
.login {
  .title {
    span {
      font: normal 400 30px '微软雅黑';
    }
    div {
      height: 30px;
      line-height: 30px;
      font-size: 14px;
    }
  }
  .login_form {
    padding: 0px 30px 30px 30px;
  }

  .van-field {
    height: 60px;
    line-height: 60px;
    font-size: 16px;
    color: #959aab;
  }

  .sms_btn {
    border: 0;
    background-color: #fff;
    color: #fa9b1c;
    font-size: 16px;
  }

  .verify_code {
    img {
      width: 115px;
    }
  }

  .login_btn {
    border: 0;
    background: linear-gradient(to right, #eeb238, #fd9717);
    font-size: 16px;
  }
}
</style>
